package com.cxs.xiaomi.web.controller;

import com.cxs.xiaomi.domain.*;
import com.cxs.xiaomi.service.AddressService;
import com.cxs.xiaomi.service.CartService;
import com.cxs.xiaomi.service.OrderDetailService;
import com.cxs.xiaomi.service.OrderService;
import com.cxs.xiaomi.service.impl.AddressServiceImpl;
import com.cxs.xiaomi.service.impl.CartServiceImpl;
import com.cxs.xiaomi.service.impl.OrderDetailServiceImpl;
import com.cxs.xiaomi.service.impl.OrderServiceImpl;
import com.cxs.xiaomi.utils.StringUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/*
 * @Author:cxs
 * @Date:2021/9/14  16:13
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@WebServlet(name = "OrderServlet", urlPatterns = "/orderservlet")
public class OrderServlet extends BaseServlet {
    private CartService cartService = new CartServiceImpl();
    private AddressService addressService = new AddressServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    private OrderDetailService orderDetailService = new OrderDetailServiceImpl();

    // 获得订单详情页面
    public String getOrderView(HttpServletRequest request, HttpServletResponse response) {
        User user = getUser(request, response);
        if (user != null) {
            List<Cart> cartList = cartService.getCart(user.getId());
            List<Address> addressList = addressService.getList(user.getId());
            request.setAttribute("cartList", cartList);
            request.setAttribute("addressList", addressList);
            return "forward:/order.jsp";
        }
        return "redirect:/login.jsp";
    }

    // 提交订单
    public String addOrder(HttpServletRequest request, HttpServletResponse response) {
        User user = getUser(request, response);
        if (user != null) {
            String aid = request.getParameter("aid");
            if (StringUtil.empty(aid)) {
                request.setAttribute("msg", "地址出错了");
                return "forward:/message.jsp";
            }
            try {
                List<Cart> cartList = cartService.getCart(user.getId());
                BigDecimal money = new BigDecimal("0");
                //计算金额
                for (Cart cart : cartList) {
                    money = money.add(cart.getMoney());
                }
                String key = StringUtil.generateUniqueKey(20);
                Order order = new Order(key, user.getId(), money, "1", new Date(), Integer.parseInt(aid));
                if (orderService.add(cartList, order)) {
                    request.setAttribute("order", order);
                    return "forward:/orderSuccess.jsp";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setAttribute("msg", "订单添加失败");
            return "forward:/message.jsp";
        }
        return "redirect:/login.jsp";
    }

    // 获取订单列表
    public String getOrderList(HttpServletRequest request, HttpServletResponse response) {
        User user = getUser(request, response);
        if (user != null) {
            List<Order> orderList = orderService.getList(user.getId());
            request.setAttribute("orderList", orderList);
            return "forward:/orderList.jsp";
        }
        return "redirect:/login.jsp";
    }

    // 订单详情
    public String getOrderDetail(HttpServletRequest request, HttpServletResponse response) {
        User user = getUser(request, response);
        if (user != null) {
            String oid = request.getParameter("oid");
            Map<String, Object> map = new HashMap<>();
            if (StringUtil.empty(oid)) {
                request.setAttribute("msg", "出错了");
                return "forward:/message.jsp";
            }
            // 获得订单
            Order order = orderService.getOrder(oid);
            // 获得订单详情
            List<OrderDetail> orderDetailList = orderDetailService.getList(oid);
            // 获得地址
            if (order != null) {
                // 获得地址
                Address address = addressService.getAddr(order.getAid());
                map.put("order", order);
                map.put("address", address);
                map.put("list", orderDetailList);
            }
            request.setAttribute("map", map);
            return "forward:/orderDetail.jsp";
        }
        return "redirect:/login.jsp";
    }

    // 修改订单状态
    public String changeStatus(HttpServletRequest request, HttpServletResponse response) {
        String oid = request.getParameter("oid");
        if (StringUtil.empty(oid)) {
            request.setAttribute("msg", "出错了");
            return "forward:/message.jsp";
        }
        orderService.updateState(oid.trim(), "4");
        return "redirect:/orderservlet?method=getOrderList";
    }

    // 管理员
    //获得所有订单信息
    public String getAllOrder(HttpServletRequest request, HttpServletResponse response) {
        List<Order> orderList = orderService.getList();
        request.setAttribute("orderList", orderList);
        return "forward:/admin/showAllOrder.jsp";
    }

    // 修改订单状态
    public String sendOrder(HttpServletRequest request, HttpServletResponse response) {
        String oid = request.getParameter("oid");
        if (StringUtil.empty(oid)) {
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("<script>alert('操作失败')</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        orderService.updateState(oid.trim(), "3");
        return "redirect:/orderservlet?method=getAllOrder";
    }

    public String searchOrder(HttpServletRequest request, HttpServletResponse response) {
        StringBuilder sb = new StringBuilder();
        List params = new ArrayList();
        sb.append(" where 1=1 ");
        String username = request.getParameter("username");
        String status = request.getParameter("status");
        if (!StringUtil.empty(username)) {
            request.setAttribute("username", username);
            StringBuilder sb1 = new StringBuilder();
            List<Address> addressList = addressService.getList(username.trim());
            if (addressList.size() > 0) {
                sb.append(" and aid in");
                sb1.append("(");
                for (int i = 0; i < addressList.size(); i++) {
                    if (i == addressList.size() - 1) {
                        sb1.append("?) ");
                    } else {
                        sb1.append("?,");
                    }
                    params.add(addressList.get(i).getId());
                }
                sb.append(sb1.toString());
            }
        }
        if (!StringUtil.empty(status)) {
            request.setAttribute("status", status);
            sb.append(" and status = ?");
            params.add(status.trim());
        }
        List<Order> orderList = orderService.getList(sb.toString(), params);
        request.setAttribute("orderList", orderList);
        return "forward:/admin/showAllOrder.jsp";
    }

    // 测试
    public void test(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("测试方法执行");
    }
}
